import sys
import socket
import string

import datetime
import time

from pahk import Interpreter

HOST="irc.twitch.tv" #Irc host
PORT=80 #Connection port. For twitch, use 6667, or if it is blocked, use 80.
NICK="" #Twitch username
OAUTH="" #OAuth code from http://twitchapps.com/tmi/
CHANNEL="" #Channel to listen to

keyPressLen=68 #Miliseconds to press each key

#Mapping between chat commands and button presses.
mapping={"a":"x",
        "b":"z",
        "start":"{Enter}",
        "select":"{LShift}",
        "up":"{UP}",
        "down":"{DOWN}",
        "left":"{LEFT}",
        "right":"{RIGHT}"}


#Connects to the twitch channel
def connect():
    ip=socket.gethostbyname(HOST)
    soc=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    soc.connect((ip,PORT))
    soc.send("PASS "+OAUTH+"\r\n")
    soc.send("NICK "+NICK+"\r\n")
    soc.send("JOIN "+CHANNEL+"\r\n")
    print "CONNECTION SUCESSFULL"
    return soc

#Interprets the irc message into the metadata and trailing parts
def parseLine(line):
    metaIndex=line.find(":",1)
    metadata=line[0:metaIndex+1]
    trailing=line[metaIndex+1:]
    return (metadata,trailing)

#Just presses buttons.    
def pressButton(interpreter,button):
    interpreter.execute_script("#UseHook\n#InstallKeybdHook\nSetKeyDelay -1,"+str(keyPressLen)+"\nSendEvent "+button)

#Reads messages from the socket into the buffer, PONGS PINGS, and mashes buttons.
def handleInput(soc,buf,interpreter):
    buf+=soc.recv(1024)
    split=[]
    
    while(True):
        index=buf.find("\r\n")
        if(index==-1):
            break;
        split.append(buf[0:index])
        buf=buf[index+2:]
        
    for line in split:
        
        message=parseLine(line)
        
        if(message[0][0:4]=="PING"):
            soc.send("PONG :"+message[1]+"\r\n")
        else:
            if("PRIVMSG" in message[0]):
            
                user=message[0][1:message[0].find("!")]
                input=message[1].lower();
                
                if input in mapping:
                    print user+" > "+input
                    pressButton(interpreter,mapping[input])
                        
                        
                
def main():
    if(NICK=="" or OAUTH=="" or CHANNEL==""):
        print "Remember to update Bot.py with your username, target channel, and oauth code!"
    else:
        soc=connect()
        buffer=""
        interpreter = Interpreter()
        while 1:
            handleInput(soc,buffer,interpreter)
        del interpreter
    
main()